/**
 * 给定5*5的数组A和B，问能否从A走到B，最少步数是多少。
 * 每次走动可以：交换相邻两行，或者交换相邻两列
 * 因为规模较小，直接广搜
 */
#include<bits/stdc++.h>
using namespace std;

using llt = long long;
using vi = vector<int>;


int H, W;
vector<vi> A, B;

bool operator < (const vector<vi> & a, const vector<vi> & b){
    for(int i=0;i<H;++i)for(int j=0;j<W;++j){
		if(a[i][j] != b[i][j]) return a[i][j] < b[i][j];
	}
	return false;
}
bool operator == (const vector<vi> & a, const vector<vi> & b){
    for(int i=0;i<H;++i)for(int j=0;j<W;++j){
		if(a[i][j] != b[i][j]) return false;
	}
	return true;
}

map<vector<vi>, int> D;


int proc(){
	if(A == B) return 0;
    D[A] = 0;
	queue<vector<vi>> q;
	q.push(A);

    int sz = 0;
	int k = 0;
	while(sz = q.size()){
		++k;
		while(sz--){
            auto h = q.front(); q.pop();

			for(int i=0;i<H-1;++i){
				auto tmp = h;
				tmp[i].swap(tmp[i + 1]);
				if(tmp == B) return k;
				auto it = D.find(tmp);
				if(it == D.end()){
					it = D.insert(it, {tmp, k});
					q.push(tmp);
				} 				
			}
		    
			for(int i=0;i<W-1;++i){
				auto tmp = h;
				for(int j=0;j<H;++j)swap(tmp[j][i], tmp[j][i + 1]);
				if(tmp == B) return k;
				auto it = D.find(tmp);
				if(it == D.end()){
					it = D.insert(it, {tmp, k});
					q.push(tmp);
				} 	
			}
		}
	}
	return -1;
}

int main(){
#ifndef ONLINE_JUDGE
    freopen("z.txt", "r", stdin);
#endif
	ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
    cin >> H >> W;
	A.assign(H, vi(W, 0));
	B.assign(H, vi(W, 0));
	for(auto & a : A)for(auto & i : a)cin>>i;
	for(auto & a : B)for(auto & i : a)cin>>i;
	cout << proc() << endl;
	return 0;
}